package com.leyou.service;

import com.leyou.common.enums.LyEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.utils.CodecUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    public Boolean check(String data, Integer type) {
        //判断类型
        User user = new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(LyEnum.USER_DATA_TYPE_ERRPR);
        }

        return userMapper.selectCount(user) == 0;
    }

    public void sendCode(String phone) {
        //生成验证码
        String code = NumberUtils.generateCode(6);
        Map<String,String> map = new HashMap();
        map.put("telphone",phone);
        map.put("code",code);
        //保存验证码
        String key = "yz"+phone;
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        amqpTemplate.convertAndSend("leyou.dx.exchange","dx.code",map);
    }

    public User queryUser(String username, String password) {
        User user1 = new User();
        user1.setUsername(username);
        User user = userMapper.selectOne(user1);
        if(user==null){
            return  null;
        }
        if(!CodecUtils.md5Hex(password,user.getSalt()).equals(user.getPassword())){
            return null;
        }
        return user;
    }
}
